/*
 * @lc app=leetcode.cn id=538 lang=typescript
 *
 * [538] 把二叉搜索树转换为累加树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：中序遍历
//  通过改变right和left的递归顺序，中序遍历为倒序
//  从最右边的叶子节点开始加

//  复杂度：O(n) O(n)

function convertBST(root: TreeNode | null): TreeNode | null {
    let sum = 0
    const traverse = (root: TreeNode | null): void => {
        if (!root) return
        // right在前，倒序
        traverse(root.right)
        //  中序遍历
        sum += root.val
        root.val = sum
        traverse(root.left)
    }
    traverse(root)
    return root
};
// @lc code=end

import { TreeNode } from "./type"
const root = TreeNode.buildTree([4, 1, 6, 0, 2, 5, 7, null, null, null, 3, null, null, null, 8])
console.log(TreeNode.printTree(convertBST(root)))

